import sys
import os
import json
from PySide6.QtWidgets import (QWidget, QVBoxLayout, QHBoxLayout, QLabel, QPushButton, 
                             QComboBox, QGroupBox, QGridLayout, QLineEdit, QMessageBox,
                             QInputDialog, QFrame)
from PySide6.QtGui import QFont, QIcon
from PySide6.QtCore import Signal

class DeviceConfigWidget(QWidget):
    """设备配置Tab组件"""
    next_clicked = Signal()  # 下一步
    prev_clicked = Signal()  # 上一步

    def __init__(self, app_data, parent=None):
        super().__init__(parent)
        self.CONFIG_FILE = app_data.CONFIG_FILE
        self.device_profiles = self.load_device_profiles()
        self.init_ui()

    def load_device_profiles(self) -> list:
        """加载设备配置"""
        if os.path.exists(self.CONFIG_FILE):
            with open(self.CONFIG_FILE, 'r', encoding='utf-8') as f:
                return json.load(f)
        return []

    def init_ui(self):
        # 设置整个标签页的布局
        layout = QVBoxLayout(self)
        layout.setContentsMargins(20, 20, 20, 20)
        layout.setSpacing(15)

        # 标题区域
        title_container = QHBoxLayout()
        title = QLabel("设备与软件配置")
        title.setFont(QFont("Arial", 18, QFont.Bold))
        title.setStyleSheet("color: #2c3e50;")
        title_container.addWidget(title)
        title_container.addStretch()
        layout.addLayout(title_container)

        # 添加一条分隔线
        line = QFrame()
        line.setFrameShape(QFrame.HLine)
        line.setFrameShadow(QFrame.Sunken)
        line.setStyleSheet("background-color: #ecf0f1;")
        layout.addWidget(line)

        # 设备选择区域
        device_group = QGroupBox("设备配置")
        device_group.setFont(QFont("Arial", 12, QFont.Bold))
        device_group.setStyleSheet("""
            QGroupBox {
                border: 1px solid #bdc3c7;
                border-radius: 6px;
                margin-top: 10px;
                padding: 15px;
                background-color: #f8f9fa;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                left: 10px;
                padding: 0 5px 0 5px;
                color: #34495e;
            }
        """)

        device_layout = QVBoxLayout(device_group)
        device_layout.setSpacing(10)

        # 设备选择和新增按钮的水平布局
        device_selection_layout = QHBoxLayout()
        device_selection_layout.setSpacing(10)

        device_selection_layout.addWidget(QLabel("选择设备型号和软件版本:"))

        self.device_combo = QComboBox()
        self.device_combo.addItems([item['name'] for item in self.device_profiles])
        self.device_combo.currentIndexChanged.connect(self.update_config_fields)
        self.device_combo.setMinimumWidth(200)
        device_selection_layout.addWidget(self.device_combo)

        # 新增配置按钮
        add_config_btn = QPushButton("新增配置")
        add_config_btn.setIcon(QIcon.fromTheme("list-add"))
        add_config_btn.clicked.connect(self.add_new_config)
        device_selection_layout.addWidget(add_config_btn)

        device_selection_layout.addStretch()
        device_layout.addLayout(device_selection_layout)

        # 配置字段区域
        fields_group = QGroupBox("列映射配置")
        fields_group.setFont(QFont("Arial", 11, QFont.Bold))
        fields_group.setStyleSheet("""
            QGroupBox {
                border: 1px solid #bdc3c7;
                border-radius: 4px;
                margin-top: 8px;
                padding: 10px;
                background-color: #ffffff;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                left: 10px;
                padding: 0 3px 0 3px;
                color: #34495e;
            }
        """)

        fields_layout = QGridLayout(fields_group)
        fields_layout.setSpacing(8)
        fields_layout.setContentsMargins(10, 10, 10, 10)

        # 表头
        header_style = "font-weight: bold; color: #2c3e50;"
        header_label = QLabel("列名称")
        header_label.setStyleSheet(header_style)
        fields_layout.addWidget(header_label, 0, 0)

        header_label2 = QLabel("CSV文件中的列名")
        header_label2.setStyleSheet(header_style)
        fields_layout.addWidget(header_label2, 0, 1)

        self.config_fields = {}
        labels = [
            "循环次数列",
            "运行状态列",
            "工步序号列",
            "充电容量列",
            "充电能量列",
            "放电容量列",
            "放电能量列",
            "充电关键词",
            "放电关键词",
            "静置关键词"
        ]
        keys = [
            "cycle_num",
            "status",
            "step",
            "ch_capacity",
            "ch_energy",
            "dch_capacity",
            "dch_energy",
            "ch_key",
            "dch_key",
            "stew_key"
        ]

        # 设置输入框的样式
        line_edit_style = """
            QLineEdit {
                border: 1px solid #bdc3c7;
                border-radius: 3px;
                padding: 5px;
                background-color: #ffffff;
            }
            QLineEdit:focus {
                border-color: #3498db;
                background-color: #f8f9fa;
            }
        """

        for i, (label, key) in enumerate(zip(labels, keys)):
            # 设置标签样式
            label_widget = QLabel(label)
            label_widget.setStyleSheet("color: #34495e;")
            fields_layout.addWidget(label_widget, i+1, 0)

            # 设置输入框
            self.config_fields[key] = QLineEdit()
            self.config_fields[key].setStyleSheet(line_edit_style)
            fields_layout.addWidget(self.config_fields[key], i+1, 1)

        device_layout.addWidget(fields_group)
        layout.addWidget(device_group)

        # 底部按钮区域
        btn_layout = QHBoxLayout()
        btn_layout.setSpacing(15)

        # 上一步按钮
        prev_btn = QPushButton("上一步：文件选择")
        prev_btn.setIcon(QIcon.fromTheme("go-previous"))
        prev_btn.setStyleSheet("""
            QPushButton {
                background-color: #95a5a6;
                color: white;
                border-radius: 4px;
                padding: 6px 12px;
            }
            QPushButton:hover {
                background-color: #7f8c8d;
            }
        """)
        prev_btn.clicked.connect(self.on_prev_clicked)

        # 删除配置按钮
        self.delete_btn = QPushButton("删除配置")
        self.delete_btn.setIcon(QIcon.fromTheme("list-remove"))
        self.delete_btn.setStyleSheet("""
            QPushButton {
                background-color: #e74c3c;
                color: white;
                border-radius: 4px;
                padding: 6px 12px;
            }
            QPushButton:hover {
                background-color: #c0392b;
            }
            QPushButton:disabled {
                background-color: #ec7063;
                color: #f5f5f5;
            }
        """)
        self.delete_btn.clicked.connect(self.delete_config)
        if len(self.device_profiles) <= 1:
            self.delete_btn.setEnabled(False)

        # 保存配置按钮
        save_btn = QPushButton("保存配置")
        save_btn.setIcon(QIcon.fromTheme("document-save"))
        save_btn.setStyleSheet("""
            QPushButton {
                background-color: #2ecc71;
                color: white;
                border-radius: 4px;
                padding: 6px 12px;
            }
            QPushButton:hover {
                background-color: #27ae60;
            }
        """)
        save_btn.clicked.connect(self.save_device_config)

        # 下一步按钮
        next_btn = QPushButton("下一步：BMS列配置")
        next_btn.setIcon(QIcon.fromTheme("go-next"))
        next_btn.setStyleSheet("""
            QPushButton {
                background-color: #3498db;
                color: white;
                border-radius: 4px;
                padding: 6px 12px;
            }
            QPushButton:hover {
                background-color: #2980b9;
            }
        """)
        next_btn.clicked.connect(self.on_next_clicked)

        btn_layout.addWidget(prev_btn)
        btn_layout.addStretch()
        btn_layout.addWidget(self.delete_btn)
        btn_layout.addWidget(save_btn)
        btn_layout.addWidget(next_btn)

        layout.addLayout(btn_layout)

        # 初始更新配置字段
        self.update_config_fields()

    def update_config_fields(self):
        """设备选项发生变化时更新配置字段"""
        device_index = self.device_combo.currentIndex()
        if 0 <= device_index < len(self.device_profiles):
            profile = self.device_profiles[device_index]
            for key, field in self.config_fields.items():
                if key in profile:
                    if isinstance(profile[key], list):
                        field.setText("、".join(profile[key]))
                    else:
                        field.setText(profile[key])

    def save_device_config(self):
        """保存设备配置"""
        current_device = self.device_combo.currentText()
        if not current_device:
            QMessageBox.warning(self, "警告", "请先选择或创建设备配置")
            return

        # 构建配置内容
        config = {"name": current_device}
        for key, field in self.config_fields.items():
            config[key] = field.text()
        
        # 检查是否存在同名配置
        found_index = -1
        for i, profile in enumerate(self.device_profiles):
            if profile["name"] == current_device:
                found_index = i
                break
        
        # 更新配置列表
        if found_index != -1:
            self.device_profiles[found_index] = config
            message = f"已更新设备配置: {current_device}"
        else:
            self.device_profiles.append(config)
            message = f"已保存新设备配置: {current_device}"

        # 保存配置到文件
        try:
            with open(self.CONFIG_FILE, 'w', encoding='utf-8') as json_file:
                json.dump(self.device_profiles, json_file, indent=False, ensure_ascii=False)
            QMessageBox.information(self, "成功", message)
        except Exception as e:
            QMessageBox.critical(self, "错误", f"保存配置失败: {str(e)}")

    def delete_config(self):
        """删除当前配置"""
        current_index = self.device_combo.currentIndex()
        if current_index < 0 or len(self.device_profiles) <= 1:
            return

        current_config_name = self.device_combo.currentText()
        reply = QMessageBox.question(
            self, "确认删除", 
            f"确定要删除配置 '{current_config_name}' 吗？\n此操作不可撤销。",
            QMessageBox.Yes | QMessageBox.No, QMessageBox.No
        )

        if reply == QMessageBox.Yes:
            # 从配置列表中移除
            del self.device_profiles[current_index]
            # 从下拉框中移除
            self.device_combo.removeItem(current_index)
            # 如果只剩一个配置，禁用删除按钮
            if len(self.device_profiles) <= 1:
                self.delete_btn.setEnabled(False)
            # 更新显示
            if self.device_profiles:
                self.update_config_fields()
            # 保存修改
            try:
                with open(self.CONFIG_FILE, 'w', encoding='utf-8') as json_file:
                    json.dump(self.device_profiles, json_file, indent=False, ensure_ascii=False)
            except Exception as e:
                QMessageBox.critical(self, "错误", f"保存配置失败: {str(e)}")

    def add_new_config(self):
        """添加新配置"""
        config_name, ok = QInputDialog.getText(self, "新增配置", "请输入新配置名称:")
        if ok and config_name:
            # 检查名称是否已存在
            if any(profile['name'] == config_name for profile in self.device_profiles):
                QMessageBox.warning(self, "名称已存在", "该配置名称已存在，请使用其他名称。")
                return

            # 创建新配置
            new_config = {
                key: "" for key in ["name"] + list(self.config_fields.keys())
            }
            new_config['name'] = config_name
            self.device_profiles.append(new_config)
            
            # 更新下拉框
            self.device_combo.addItem(config_name)
            self.device_combo.setCurrentText(config_name)
            
            # 清空输入字段
            for field in self.config_fields.values():
                field.clear()
                
            # 启用删除按钮
            if len(self.device_profiles) > 1:
                self.delete_btn.setEnabled(True)

    def get_current_config(self):
        """获取当前设备配置"""
        config = {}
        for key, field in self.config_fields.items():
            config[key] = field.text().strip()
        return config

    def on_prev_clicked(self):
        """上一步按钮点击事件"""
        # 由主窗口处理切换Tab
        self.prev_clicked.emit()

    def on_next_clicked(self):
        """下一步按钮点击事件"""
        # 由主窗口处理切换Tab
        self.next_clicked.emit()
